<template>
  <q-card flat>
    <q-card-section>
      <CurrentTitle class="text-h6" />
    </q-card-section>
    <q-separator inset />
    <!-- 主要内容 -->
    <q-card-section>
      <p class="text-grey-6">多联系方式列表，可根据地址自动定位地图。</p>
      <q-table
        :data="table.tableContentData"
        :columns="table.columns"
        :visibleColumns="table.visibleColumns"
        row-key="index"
        :loading="table.loading"
        :pagination.sync="table.initialPagination"
        rows-per-page-label="每页显示"
        flat
        bordered
        wrap-cells
        :dense="$q.screen.lt.md"
        :separator="table.separator"
        :hide-bottom="table.hideBottom"
      >
        <template v-slot:body-cell-Action="props">
          <q-td :props="props">
            <q-btn-group flat>
              <q-btn
                icon="mdi-delete"
                label="删除"
                size="sm"
                flat
                color="negative"
                @click="getDeleteRow(props.row)"
              />
              <q-btn
                icon="mdi-table-edit"
                label="编辑"
                size="sm"
                flat
                color="primay"
                @click="getEditRow(props.row)"
              />
            </q-btn-group>
          </q-td>
        </template>
        <template v-slot:body-cell-Status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.Status"
              name="Status"
              disable
            />
          </q-td>
        </template>
        <template v-slot:pagination>
          <q-pagination
            v-model="table.initialPagination.current"
            :max="table.initialPagination.page"
            :boundary-links="true"
            @click="getList(form.model, table.initialPagination.current)"
          >
          </q-pagination>
        </template>
        <template v-slot:loading>
          <q-inner-loading
            showing
            color="primary"
          />
        </template>
      </q-table>
      <!-- 对话框-删除确认 -->
      <q-dialog v-model="dialog.delConfirm">
        <q-card>
          <q-card-section class="row items-center">
            <q-avatar
              icon="mdi-alert-circle-outline"
              text-color="negative"
            />
            <span class="q-ml-sm text-negative">确定要删除所选记录吗？</span>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              flat
              label="取消"
              v-close-popup
            />
            <q-btn
              flat
              label="确定删除"
              color="negative"
              v-close-popup
              @click="deleteRows(deleteID)"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card-section>
    <q-card-section>
      <q-tabs
        v-model="tabPanel.tab"
        dense
        class="text-grey"
        active-color="primary"
        indicator-color="primary"
        align="justify"
        narrow-indicator
      >
        <q-tab
          name="add"
          label="添加"
        />
        <q-tab
          name="edit"
          label="编辑"
          :disable="tabPanel.disable"
        />
      </q-tabs>

      <q-separator />

      <q-tab-panels
        v-model="tabPanel.tab"
        animated
        ref="tabPanels"
      >
        <q-tab-panel name="add">
          <q-form
            class="col-12 col-lg-11 col-xl-9"
            @submit.prevent.stop="addItem"
            @reset="formReset"
            ref="addItem"
          >
            <div class="row q-col-gutter-md">
              <div class="col col-md-10">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.BranchName"
                  label="公司名称"
                  name="BranchName"
                />
              </div>
              <div class="col col-md-2">
                <q-toggle
                  v-model="form.Status"
                  name="Status"
                  label="是否审核"
                  left-label
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.Province.model"
                  :options="form.Province.options"
                  label="省/直辖市/自治区"
                  name="Province"
                  options-selected-class="text-primary"
                  @input="getCity(form.Province.model.value)"
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.City.model"
                  :options="form.City.options"
                  label="城市"
                  name="City"
                  options-selected-class="text-primary"
                  @input="getDistrict(form.City.model.value)"
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.District.model"
                  :options="form.District.options"
                  label="区/县"
                  name="District"
                  options-selected-class="text-primary"
                />
              </div>
              <div class="col col-md-12">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Address"
                  label="详细地址"
                  name="Address"
                >
                  <template v-slot:append>
                    <q-btn
                      color="primary"
                      dense
                      flat
                      label="定位地图"
                      @click="getGeoCoding"
                    />
                    <q-btn
                      rounded
                      dense
                      flat
                      icon="mdi-information-outline"
                      size='sm'
                    >
                      <q-tooltip>
                        按地址信息，自动定位地图
                      </q-tooltip>
                    </q-btn>
                  </template>
                </q-input>
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Tel"
                  label="联系电话"
                  name="Tel"
                />
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Lng"
                  label="地图经度"
                  name="Lng"
                />
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Lat"
                  label="地图纬度"
                  name="Lat"
                />
              </div>
              <div class="col col-md-12">
                <baidu-map
                  id="addressMap"
                  :center="map.center"
                  :zoom="map.zoom"
                  :scroll-wheel-zoom="true"
                  @click="addOverlay"
                  @moving="syncCenterAndZoom"
                  @moveend="syncCenterAndZoom"
                  @zoomend="syncCenterAndZoom"
                >
                  <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                  <bm-geolocation
                    anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                    :showAddressBar="true"
                    :autoLocation="true"
                  ></bm-geolocation>
                  <bm-marker
                    :position="map.marker.position"
                    :dragging="true"
                    animation="BMAP_ANIMATION_BOUNCE"
                  />
                </baidu-map>
              </div>
            </div>
            <q-separator class="q-my-md" />
            <div class="row q-col-gutter-md">
              <q-space />
              <div class="col col-md-2">
                <q-btn
                  label="重置表单"
                  type="reset"
                  flat
                  color="secondary"
                  class="full-width bg-grey-4"
                />
              </div>
              <div class="col col-md-2">
                <q-btn
                  label="确定添加"
                  type="submit"
                  color="white"
                  flat
                  class="full-width bg-primary"
                />
              </div>
            </div>
          </q-form>
        </q-tab-panel>

        <q-tab-panel name="edit">
          <q-form
            class="col-12 col-lg-11 col-xl-9"
            @submit.prevent.stop="editItem"
            @reset="formReset"
            ref="editItem"
          >
            <div class="row q-col-gutter-md">
              <div class="col col-md-10">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.BranchName"
                  label="公司名称"
                  name="BranchName"
                />
              </div>
              <div class="col col-md-2">
                <q-toggle
                  v-model="form.Status"
                  name="Status"
                  label="是否审核"
                  left-label
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.Province.model"
                  :options="form.Province.options"
                  label="省/直辖市/自治区"
                  name="Province"
                  options-selected-class="text-primary"
                  @input="getCity(form.Province.model.value)"
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.City.model"
                  :options="form.City.options"
                  label="城市"
                  name="City"
                  options-selected-class="text-primary"
                  @input="getDistrict(form.City.model.value)"
                />
              </div>
              <div class="col col-md-4">
                <q-select
                  outlined
                  dense
                  v-model="form.District.model"
                  :options="form.District.options"
                  label="区/县"
                  name="District"
                  options-selected-class="text-primary"
                />
              </div>
              <div class="col col-md-12">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Address"
                  label="详细地址"
                  name="Address"
                >
                  <template v-slot:append>
                    <q-btn
                      color="primary"
                      dense
                      flat
                      label="定位地图"
                      @click="getGeoCoding"
                    />
                    <q-btn
                      rounded
                      dense
                      flat
                      icon="mdi-information-outline"
                      size='sm'
                    >
                      <q-tooltip>
                        按地址信息，自动定位地图
                      </q-tooltip>
                    </q-btn>
                  </template>
                </q-input>
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Tel"
                  label="联系电话"
                  name="Tel"
                />
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Lng"
                  label="地图经度"
                  name="Lng"
                />
              </div>
              <div class="col col-md-4">
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  v-model="form.Lat"
                  label="地图纬度"
                  name="Lat"
                />
                <q-input
                  hide-bottom-space
                  outlined
                  v-model="form.ID"
                  label="ID"
                  name="id"
                  class="hidden"
                />
              </div>
              <div class="col col-md-12">
                <baidu-map
                  id="addressMap"
                  :center="map.center"
                  :zoom="map.zoom"
                  :scroll-wheel-zoom="true"
                  @click="addOverlay"
                  @moving="syncCenterAndZoom"
                  @moveend="syncCenterAndZoom"
                  @zoomend="syncCenterAndZoom"
                >
                  <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                  <bm-geolocation
                    anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                    :showAddressBar="true"
                    :autoLocation="true"
                  ></bm-geolocation>
                  <bm-marker
                    :position="map.marker.position"
                    :dragging="true"
                    animation="BMAP_ANIMATION_BOUNCE"
                  />
                </baidu-map>
              </div>
            </div>
            <q-separator class="q-my-md" />
            <div class="row q-col-gutter-md">
              <q-space />
              <div class="col col-md-2">
                <q-btn
                  label="取消"
                  type="reset"
                  flat
                  class="full-width"
                />
              </div>
              <div class="col col-md-2">
                <q-btn
                  label="提交编辑"
                  type="submit"
                  color="white"
                  flat
                  class="full-width bg-primary"
                />
              </div>
            </div>
          </q-form>
        </q-tab-panel>
      </q-tab-panels>
    </q-card-section>
  </q-card>
</template>

<script>
import CurrentTitle from 'components/common/CurrentTitle/CurrentTitle'
import { mapMutations } from 'vuex'
import Region from './Region'

export default {
  name: 'PageContact',
  components: {
    CurrentTitle
  },
  props: {},
  data () {
    return {
      // tab
      tabPanel:{
        tab: 'add',
        disable: true
      },
      // ---------- 百度地图
      map: {
        center: {
          lng: 116.404844,
          lat: 39.914935
        },
        zoom: 12,
        // 标注点
        marker: {
          position: {
            lng: null,
            lat: null
          }
        },
      },
      // ---------- 表单
      form:{
        Province:{
          model: null,
          options: [],
        },
        City:{
          model: null,
          options: [],
        },
        District:{
          model: null,
          options: [],
        },
        tempRegion:[],
        BranchName: '',
        Address: '',
        Tel: '',
        Status: true,
        Lng: 0,// 经度
        Lat: 0,// 纬度
        ID:''
      },
      // ---------- 表格
      table: {
        // 默认$Api参数
        defaultCategory: -1,
        defaultPageIndex: 1,
        // 初始化分页
        initialPagination: {
          sortBy: 'desc',
          descending: false,
          page: 1,
          rowsPerPage: this.$store.state.default.rowsPerPage,
          current: 1,
          rowsNumber: 0 //if getting data from a server
        },
        hideBottom: false,
        // 分割线模式可选值：horizontal (default)', 'vertical', 'cell', 'none'
        separator: 'horizontal',
        loading: true,
        // 可见列
        visibleColumns: [ 'BranchName', 'Address', 'Tel', 'Status', 'Action'],
        columns: [
          {
            name: 'index',
            required: true,
            label: '序号',
            align: 'center',
            field: 'index'
          },
          { name: 'ID', align: 'center', label: 'ID', field: 'ID', style: 'max-width:50px'},
          { name: 'BranchName', align: 'center', label: '公司/分公司名称', field: 'BranchName' },
          { name: 'Province', align: 'center', label: '省/自治区/直辖市', field: 'Province' },
          { name: 'City', align: 'center', label: '市/地区', field: 'City' },
          { name: 'District', align: 'center', label: '区/县', field: 'District' },
          { name: 'Address', align: 'center', label: '详细地址', field: 'Address' },
          { name: 'Tel', align: 'center', label: '电话', field: 'Tel' },
          { name: 'Status', align: 'center', label: '审核', field: 'Status' },
          { name: 'Action', align: 'center', label: '操作', field: '', style: 'min-width:220px' },
        ],
        tableContentData: [],
      },
      // ---------- 对话框
      dialog: {
        delConfirm: false,
      },
      deleteID: [],
      Region
    }
  },
  methods: {
    // 获得客户端IP，定位城市，并初始化地图和行政区划联动下拉框
    getIPLocation() {
      const _params = {
        ak: this.$store.state.BaiduAK,
        coor: 'bd09ll',
      }
      this.$jsonp(this.$utils.baiduIPLocationAPI, _params).then( result => {
        // console.log(result)
        const _Province = result.content.address_detail.province
        const _City = result.content.address_detail.city
        this.form.Province.model = new Object()
        this.Region.map( item => {
          if ( item.label === _Province ) {
            this.form.Province.model.label = _Province
            this.form.Province.model.value = item.value
            this.getCity(item.value)
            this.form.City.model = new Object()
            item.children.map( cityItem => {
              if ( cityItem.label === _City ) {
                this.form.City.model.label = _City
                this.form.City.model.value = cityItem.value
                this.getDistrict(cityItem.value)
              }
            })
          }
        })
        this.map.center.lng = result.content.point.x
        this.form.Lng = result.content.point.x
        this.map.marker.position.lng = result.content.point.x
        this.map.center.lat = result.content.point.y
        this.form.Lat = result.content.point.y
        this.map.marker.position.lat = result.content.point.x
      }).catch (err => {
        console.log(err)
      })
    },
    // 地理编码，根据地址定位地图
    getGeoCoding() {
      const _params = {
        ak: this.$store.state.BaiduAK,
        output: 'json',
        address: this.form.Address,
        city: this.form.City.model.label
      }
      // console.log(_params.address)
      this.$jsonp(this.$utils.baiduGeoCodingAPI, _params).then( result => {
        // console.log(result)
        this.map.center.lng = result.result.location.lng
        this.form.Lng = result.result.location.lng
        this.map.marker.position.lng = result.result.location.lng
        this.map.center.lat = result.result.location.lat
        this.form.Lat = result.result.location.lat
        this.map.marker.position.lat = result.result.location.lat
        this.map.zoom = 16
      })
    },
    // 点击添加覆盖物——点
    addOverlay (e) {
      const { lng, lat } = e.point
        this.map.center.lng = lng
        this.form.Lng = lng
        this.map.marker.position.lng = lng
        this.map.center.lat = lat
        this.form.Lat = lat
        this.map.marker.position.lat = lat
    },
    // 地图拖动、缩放获取动态中心坐标和缩放值
    syncCenterAndZoom (e) {
      const { lng, lat} = e.target.getCenter()
      this.map.center.lng = lng
      this.form.Lng = lng
      this.map.center.lat = lat
      this.form.Lat = lat
      this.map.zoom = e.target.getZoom()
    },
    // 获取列表
    getList(currentPage) {
      const _params = {
        pageIndex:currentPage,
        pageSize:this.table.initialPagination.rowsPerPage,
      }
      this.$api.ContactParams('', 'get', _params).then (result => {
        // console.log(result)
        this.table.tableContentData = result.data
        this.table.initialPagination.rowsNumber = result.count
        this.table.initialPagination.page = Math.ceil(this.table.initialPagination.rowsNumber / this.table.initialPagination.rowsPerPage)
        // 生成序号
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
        })
        // 关闭加载动画
        this.table.loading = false
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 动态分页(下拉选择每页显示条数)
    requestPagination(props) {
      this.table.initialPagination.rowsPerPage = this.$utils.dynamicPagination(props)
      this.getList(this.table.defaultPageIndex)
    },
    // 获取省市区联动下拉框列表数据
    // -------省
    getProvince() {
      this.Region.map( item => {
        // console.log(item)
        this.form.Province.options.push({
          label: item.label,
          value: item.value
        })
      })
    },
    // -------市
    getCity(value){
      this.form.City.model = null
      this.form.City.options = []
      this.Region.map( item => {
        if ( item.value === value) {
          this.form.tempRegion = item.children
          item.children.map( cityItem => {
            this.form.City.options.push({
              label: cityItem.label,
              value: cityItem.value
            })
          })
        }
      })
    },
    // -------区、县
    getDistrict(value){
      this.form.District.model = null
      this.form.District.options = []
      this.form.tempRegion.map( item => {
        if ( item.value === value) {
          item.children.map( districtItem => {
            this.form.District.options.push({
              label: districtItem.label,
              value: districtItem.value
            })
          })
        }
      })
    },
    // 获取所有过期ID值数组
    getExpiredRows() {
      const _nowDate = Date.parse(new Date())
      this.table.tableContentData.map((row) => {
        const _stopDate = new Date (row.StopDate).getTime()
        if ( _stopDate < _nowDate ) {
          this.deleteID.push( row.ID)
        }
      })
      if ( this.deleteID.length > 0 ) {
        this.dialog.delConfirm = true
      } else {
        this.$utils.notify('没有过期记录','red-8')
      }
    },
    // 获取单条删除的row信息
    getDeleteRow(row) {
      this.deleteID = []
      this.deleteID.push(row.ID)
      this.dialog.delConfirm = true
    },
    // 提交服务器并删除本地预存信息
    deleteRows(rowid) {
      // 删除
      const _ids = rowid
      this.$api.ContactData('', 'delete', _ids).then (result => {
        // console.log(result)
         if ( result === 'success') {
          //  重新请求数据列表
           this.getList(this.table.defaultPageIndex)
           this.$utils.notify('删除成功！', 'positive')
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
      this.deleteID = []
      this.table.selected = []
    },
    // 添加
    addItem(evt) {
      const _addItemResult = this.$utils.formatFormData(evt)
      // console.log(_addItemResult)
      this.$api.ContactData('', 'post', _addItemResult).then( result => {
        // console.log(result)
        if ( result === 'success') {
          this.getList(this.table.defaultPageIndex)
          this.$utils.notify('添加成功！', 'positive')
        } else if ( result === 'error' ) {
          this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
        }
      }).catch( err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 获得编辑的行数据
    getEditRow(value) {
      // console.log(value)
      this.form.BranchName = value.BranchName
      this.form.Address = value.Address
      this.form.Tel = value.Tel
      this.form.Lng = value.Lng
      this.form.Lat = value.Lat
      this.form.Status = value.Status
      this.form.ID = value.ID
      this.form.Province.model = new Object()
      this.Region.map( item => {
        if ( item.value === value.Province ) {
          this.form.Province.model.value = value.Province
          this.form.Province.model.label = item.label
          this.getCity(item.value)
          item.children.map ( cityItem => {
            if ( cityItem.value === value.City ) {
              this.form.City.model = new Object()
              this.form.City.model.value = value.City
              this.form.City.model.label = cityItem.label
              this.getDistrict(cityItem.value)
              cityItem.children.map ( districtItem => {
                if ( districtItem.value === value.District ) {
                  this.form.District.model = new Object()
                  this.form.District.model.value = value.District
                  this.form.District.model.label = districtItem.label
                }
              })
            }
          }) 
        }
      })
      this.$refs.tabPanels.goTo('edit')
      this.tabPanel.disable = false
      this.getGeoCoding()
      // console.log(this.tabPanel.tab)
    },
    // 提交编辑数据
    editItem (evt) {
      const _editRowResult = this.$utils.formatFormData(evt)
      this.$api.ContactData(this.form.ID, 'put', _editRowResult).then (result => {
        // console.log(result)
         if ( result === 'success') {
          this.formReset()
          this.getList(this.table.defaultPageIndex)
          this.$utils.notify('数据修改成功！', 'positive')
          // 重新请求数据列表
          this.getCategoryList(this.form.model)
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else if ( result === 'exist' ) {
           this.$utils.notify('该分类已存在，请更换分类名称', 'red-10')
         }
      }).catch (err => {
        console.log(err)
      })
    },
    // 重置表单
    formReset() {
      this.tabPanel.disable = true
      this.$refs.tabPanels.goTo('add')
      this.form.BranchName = ''
      this.form.Address = ''
      this.form.Tel = ''
      this.form.Lng = ''
      this.form.Lat = ''
      this.form.Status = true
      this.form.ID = ''
      this.getProvince()
      this.getIPLocation()
    },
    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  mounted() {
    this.getList(this.table.defaultPageIndex)
    this.getProvince()
    this.getIPLocation()
  },
}
</script>
<style scoped>
#addressMap {
  height: 500px;
  width: 100%;
  margin: 0 auto;
}
</style>
